package com.neasho.neashoadminv1.infrastructure.aspect

import cn.hutool.json.JSONUtil
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component


@Aspect
@Component
class LoggingAspect {

    // 使用文件级 logger
    companion object {
        private val log: Logger = LoggerFactory.getLogger(LoggingAspect::class.java)
    }

    /**
     * 切入点：拦截所有 service 包下的方法
     */
    @Around("execution(* com.neasho.neashoadminv1..*.*(..))")
    fun logMethodCall(joinPoint: ProceedingJoinPoint): Any? {
        val className = joinPoint.target::class.java.simpleName
        val methodName = joinPoint.signature.name
        val args = joinPoint.args

        log.info("👉 Method invoked: {}.{} with args: {}", className, methodName, args.contentToString())

        val startTime = System.currentTimeMillis()
        return try {
            val result = joinPoint.proceed()
            val duration = System.currentTimeMillis() - startTime
            log.info("👈 Method returned: {}.{} in {} ms, result: {}", className, methodName, duration, JSONUtil.toJsonStr(result))
            result
        } catch (e: Throwable) {
            log.error("❌ Method threw exception: {}.{}", className, methodName, e)
            throw e
        }
    }
}